<?php

namespace app\http;

use app\admin\model\Token;
use think\Db;
use think\facade\Cache;
use think\facade\Request;
use Overtrue\EasySms\EasySms;

class SMSCode
{
    public $sms;

    public function setSMS(array $config = null)
    {
        # code...
        if (\is_null($config)) {
            $config = [
                // HTTP 请求的超时时间（秒）
                'timeout' => 5.0,
    
                // 默认发送配置
                'default' => [
                    // 网关调用策略，默认：顺序调用
                    'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
    
                    // 默认可用的发送网关
                    'gateways' => [
                        'aliyun',
                    ],
                ],
                // 可用的网关配置
                'gateways' => [
                    'errorlog' => [
                        'file' => '/tmp/easy-sms.log',
                    ],
                    'aliyun' => [
                        'access_key_id' => 'LTAI4Frzzr5Pc5YMztHRABds',
                        'access_key_secret' => 'IqbaXHUbBkc9vWooGfhoc42IVeseM6',
                        'sign_name' => '商企智慧记',
                    ],
                    //...
                ],
            ];
        }

        $this->sms = new EasySms($config);
        return $this;
    }

    public function send($phone = null, $code = 0000)
    {
        $code = $code ?: random_int(1000, 9999);
        $ttl = 5*60;
        $key = $phone;
        if (Cache::has($key)) {
            return $key;
        }
        $res = $this->sms->send($phone, [
            'content'  => "您的验证码为: $code",
            'template' => 'SMS_177241982',
            'data' => [
                'code' => $code
            ],
        ]);
        if ($res) {
            Cache::tag('sms-token')->remember($key, $code, $ttl);
            return $key;
        }
        return false;
    }

    public function validate($key = null, $code = 0000)
    {
        if (Cache::has($key) && (Cache::get($key)) == $code) {
            Cache::rm($key);
            return true;
            # code...
        } else {
            # code...
            return false;
        }
    }

    // Route::get('test', function() {
    //     $t = new \app\http\SMSCode();
    //     $t->setSMS();
    //     // dump($t);exit();
    //     $res = $t->send('15172480645');
    //     dump($res);
    //     if($res) {
    //         return $t->validate($res, \think\facade\Request::param('code', 0000));
    //     }
    // });

}